<template>
  <div class="behavior-management-container">
    <div class="page-header">
      <h1 class="page-title">不文明行为管理</h1>
      <p class="page-description">管理和处理游客举报的不文明行为</p>
    </div>

    <el-row :gutter="20">
      <!-- 左侧景点列表 -->
      <el-col :xs="24" :md="8">
        <el-card class="spot-list-card">
          <template #header>
            <div class="card-header">
              <span>景点列表</span>
              <el-input
                v-model="searchQuery"
                placeholder="搜索景点名称"
                class="search-input"
                clearable
                prefix-icon="Search"
              />
            </div>
          </template>

          <el-table
            :data="filteredSpots"
            style="width: 100%"
            v-loading="loading"
            @row-click="handleSpotClick"
            highlight-current-row
          >
            <el-table-column prop="OBJECTID" label="ID" width="60" />
            <el-table-column prop="SpotName" label="景点名称" />
            <el-table-column label="举报数量" width="100" align="center">
              <template #default="scope">
                <span class="report-count-badge">
                  {{ scope.row.UncivilizedBehaviorReportCount || 0 }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="scope">
                <el-button size="small" type="primary" plain @click.stop="handleSpotClick(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧举报列表 -->
      <el-col :xs="24" :md="16">
        <el-card class="report-list-card" v-if="selectedSpot">
          <template #header>
            <div class="card-header">
              <span>{{ selectedSpot.SpotName }} - 不文明行为举报列表</span>
              <div class="header-actions">
                <el-select v-model="statusFilter" placeholder="状态筛选" class="status-filter">
                  <el-option label="全部" value="" />
                  <el-option label="待处理" value="pending" />
                  <el-option label="已处理" value="processed" />
                </el-select>
                <el-button type="primary" size="small" @click="refreshReports">刷新</el-button>
              </div>
            </div>
          </template>

          <div v-if="reports.length === 0" class="empty-reports">
            <el-empty description="暂无举报信息" />
          </div>

          <el-table
            v-else
            :data="filteredReports"
            style="width: 100%"
            @row-click="handleReportClick"
          >
            <el-table-column prop="id" label="举报ID" width="120" :show-overflow-tooltip="true" />
            <el-table-column label="类型" width="120">
              <template #default="scope">
                <el-tag :type="getBehaviorTypeTag(scope.row.type)">
                  {{ getBehaviorTypeText(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="严重程度" width="100">
              <template #default="scope">
                <el-rate
                  v-model="scope.row.severity"
                  disabled
                  :colors="severityColors"
                  :max="5"
                  text-color="#ff9900"
                />
              </template>
            </el-table-column>
            <el-table-column label="举报时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.reportTime) }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status === 'pending' ? 'danger' : 'success'">
                  {{ scope.row.status === 'pending' ? '待处理' : '已处理' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === 'pending'"
                  type="primary"
                  size="small"
                  @click.stop="openProcessDialog(scope.row)"
                >
                  处理
                </el-button>
                <el-button
                  v-else
                  type="info"
                  size="small"
                  @click.stop="viewProcessResult(scope.row)"
                >
                  查看结果
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card v-else class="no-spot-selected">
          <el-empty description="请选择一个景点查看举报信息" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 举报详情抽屉 -->
    <el-drawer
      v-model="showReportDrawer"
      title="举报详情"
      direction="rtl"
      size="50%"
    >
      <div v-if="currentReport" class="report-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="举报ID">
            {{ currentReport.id }}
          </el-descriptions-item>
          <el-descriptions-item label="景点名称">
            {{ selectedSpot?.SpotName || '未知景点' }}
          </el-descriptions-item>
          <el-descriptions-item label="不文明行为类型">
            <el-tag :type="getBehaviorTypeTag(currentReport.type)">
              {{ getBehaviorTypeText(currentReport.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发生时间">
            {{ formatDate(currentReport.date) }}
          </el-descriptions-item>
          <el-descriptions-item label="举报时间">
            {{ formatDate(currentReport.reportTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="严重程度">
            <el-rate
              v-model="currentReport.severity"
              disabled
              :colors="severityColors"
              :max="5"
            />
          </el-descriptions-item>
          <el-descriptions-item label="举报人">
            {{ currentReport.reporter }}
          </el-descriptions-item>
          <el-descriptions-item label="联系方式" v-if="currentReport.contact">
            {{ currentReport.contact }}
          </el-descriptions-item>
          <el-descriptions-item label="详细描述">
            {{ currentReport.description }}
          </el-descriptions-item>
          <el-descriptions-item label="照片" v-if="currentReport.imageBase64">
            <el-image
              :src="currentReport.imageBase64"
              :preview-src-list="[currentReport.imageBase64]"
              fit="contain"
              style="max-width: 100%; max-height: 300px;"
            />
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentReport.status === 'pending' ? 'danger' : 'success'">
              {{ currentReport.status === 'pending' ? '待处理' : '已处理' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理结果" v-if="currentReport.status === 'processed'">
            {{ currentReport.processResult }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="drawer-actions">
          <el-button
            v-if="currentReport.status === 'pending'"
            type="primary"
            @click="openProcessDialog(currentReport)"
          >
            处理此举报
          </el-button>
          <el-button @click="showReportDrawer = false">关闭</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 处理举报对话框 -->
    <el-dialog
      v-model="showProcessDialog"
      title="处理不文明行为举报"
      width="40%"
    >
      <el-form :model="processForm" label-position="top">
        <el-form-item label="处理结果" required>
          <el-select v-model="processForm.action" placeholder="请选择处理方式" class="full-width">
            <el-option label="已教育游客" value="educated" />
            <el-option label="已清理现场" value="cleaned" />
            <el-option label="已修复设施" value="repaired" />
            <el-option label="已罚款处理" value="fined" />
            <el-option label="已报警处理" value="reported" />
            <el-option label="其他处理方式" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理详情">
          <el-input
            v-model="processForm.details"
            type="textarea"
            :rows="4"
            placeholder="请输入处理详情"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showProcessDialog = false">取消</el-button>
          <el-button type="primary" @click="processReport" :loading="processing">
            确认处理
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 处理结果查看对话框 -->
    <el-dialog
      v-model="showResultDialog"
      title="处理结果"
      width="30%"
    >
      <div v-if="currentReport" class="process-result">
        <p><strong>处理时间：</strong> {{ formatDate(currentReport.processTime) }}</p>
        <p><strong>处理结果：</strong> {{ currentReport.processResult }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showResultDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'

// 状态变量
const loading = ref(true)
const searchQuery = ref('')
const selectedSpotId = ref<number | null>(null)
const selectedSpotName = ref('')
const reports = ref<any[]>([])
const statusFilter = ref('')
const showReportDrawer = ref(false)
const currentReport = ref<any>(null)
const showProcessDialog = ref(false)
const showResultDialog = ref(false)
const processing = ref(false)

// 图层
let featureLayer: __esri.FeatureLayer

// 处理表单
const processForm = ref({
  action: '',
  details: ''
})

// 严重程度颜色
const severityColors = ['#67C23A', '#E6A23C', '#F56C6C']

// 景点数据结构
interface SpotInfo {
  OBJECTID: number;
  SpotName: string;
  UncivilizedBehaviorReportCount: number;
}

// 景点列表
const spotList = ref<SpotInfo[]>([])

// 过滤后的景点列表
const filteredSpots = computed(() => {
  if (!searchQuery.value) return spotList.value

  return spotList.value.filter(spot =>
    spot.SpotName &&
    spot.SpotName.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 过滤后的举报列表
const filteredReports = computed(() => {
  if (!statusFilter.value) return reports.value

  return reports.value.filter(report => report.status === statusFilter.value)
})

// 初始化
onMounted(async () => {
  await initFeatureLayer()
  await loadSpots()
})

// 初始化图层
const initFeatureLayer = async () => {
  // 创建要素图层
  featureLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/2irArZCaO94Te7ab/arcgis/rest/services/ScenicPointLayer/FeatureServer/0',
    outFields: ['*']
  })
}

// 加载景点数据
const loadSpots = async () => {
  loading.value = true
  try {
    // 查询所有要素
    const query = featureLayer.createQuery()
    query.where = '1=1' // 查询所有记录
    query.outFields = ['OBJECTID', 'SpotName', 'UncivilizedBehaviorReportCount']

    const result = await featureLayer.queryFeatures(query)

    // 将查询结果转换为简单的对象数组
    spotList.value = result.features.map(feature => ({
      OBJECTID: feature.attributes.OBJECTID,
      SpotName: feature.attributes.SpotName || `景点 #${feature.attributes.OBJECTID}`,
      UncivilizedBehaviorReportCount: feature.attributes.UncivilizedBehaviorReportCount || 0
    }))

    loading.value = false
  } catch (error) {
    console.error('加载景点数据失败', error)
    ElMessage.error('加载景点数据失败')
    loading.value = false
  }
}

// 当前选中的景点
const selectedSpot = ref<SpotInfo | null>(null)

// 处理景点点击
const handleSpotClick = (row: SpotInfo) => {
  selectedSpot.value = row
  selectedSpotId.value = row.OBJECTID
  selectedSpotName.value = row.SpotName
  loadReports(row.OBJECTID)
}

// 加载举报数据
const loadReports = async (spotId: number) => {
  try {
    console.log(`加载景点 #${spotId} 的举报数据`)

    // 查询景点数据
    const query = featureLayer.createQuery()
    query.where = `OBJECTID = ${spotId}`
    query.outFields = ['UncivilizedBehaviorReportMessageJSON', 'UncivilizedBehaviorReportCount']

    const result = await featureLayer.queryFeatures(query)
    if (result.features.length === 0) {
      console.log(`未找到景点 #${spotId} 的数据`)
      reports.value = []
      return
    }

    const feature = result.features[0]
    console.log('获取到的景点数据', feature.attributes)

    if (!feature.attributes.UncivilizedBehaviorReportMessageJSON) {
      console.log('景点没有举报数据')
      reports.value = []
      return
    }

    try {
      // 定义举报数据类型
      interface ReportData {
        id: string;
        type: string;
        date: string;
        description: string;
        severity: number;
        imageBase64?: string;
        contact?: string;
        reporter: string;
        status: 'pending' | 'processed';
        processResult?: string;
        processTime?: string;
        reportTime: string;
      }

      const parsedData = JSON.parse(feature.attributes.UncivilizedBehaviorReportMessageJSON)
      if (Array.isArray(parsedData)) {
        reports.value = parsedData as ReportData[]
      } else {
        console.error('举报数据不是数组格式')
        reports.value = []
        return
      }

      // 按举报时间倒序排序
      reports.value.sort((a, b) => {
        return new Date(b.reportTime).getTime() - new Date(a.reportTime).getTime()
      })

      // 检查待处理数量是否与实际匹配
      const pendingReports = reports.value.filter(report => report.status === 'pending')
      const pendingCount = pendingReports.length
      const storedCount = feature.attributes.UncivilizedBehaviorReportCount || 0

      console.log(`待处理数量: 实际=${pendingCount}, 存储=${storedCount}`)

      // 如果不匹配，更新存储的数量
      if (pendingCount !== storedCount) {
        console.log('待处理数量不匹配，正在更新...')
        await updatePendingReportCount(spotId, reports.value)
      }
    } catch (e) {
      console.error('解析举报数据失败', e)
      reports.value = []
    }
  } catch (error) {
    console.error('加载举报数据失败', error)
    ElMessage.error('加载举报数据失败')
  }
}

// 刷新举报数据
const refreshReports = async () => {
  if (selectedSpot.value && selectedSpotId.value) {
    try {
      // 先刷新景点数据
      await loadSpots()

      // 然后加载当前选中景点的举报数据
      await loadReports(selectedSpotId.value)

      // 更新选中的景点信息
      const updatedSpot = spotList.value.find(spot => spot.OBJECTID === selectedSpotId.value)
      if (updatedSpot) {
        selectedSpot.value = updatedSpot
      }

      ElMessage.success('举报数据已刷新')
    } catch (error) {
      console.error('刷新数据失败', error)
      ElMessage.error('刷新数据失败')
    }
  }
}

// 处理举报点击
const handleReportClick = (row: any) => {
  currentReport.value = row
  showReportDrawer.value = true
}

// 打开处理对话框
const openProcessDialog = (report: any) => {
  currentReport.value = report
  processForm.value = {
    action: '',
    details: ''
  }
  showProcessDialog.value = true
  showReportDrawer.value = false
}

// 查看处理结果
const viewProcessResult = (report: any) => {
  currentReport.value = report
  showResultDialog.value = true
}

// 处理举报
const processReport = async () => {
  if (!processForm.value.action) {
    ElMessage.warning('请选择处理方式')
    return
  }

  processing.value = true

  try {
    if (!selectedSpotId.value || !currentReport.value) {
      throw new Error('数据不完整')
    }

    // 生成处理结果文本
    let resultText = ''
    switch (processForm.value.action) {
      case 'educated':
        resultText = '已对相关游客进行教育'
        break
      case 'cleaned':
        resultText = '已清理现场'
        break
      case 'repaired':
        resultText = '已修复受损设施'
        break
      case 'fined':
        resultText = '已对违规行为进行罚款处理'
        break
      case 'reported':
        resultText = '已报警处理'
        break
      case 'other':
        resultText = '其他处理方式'
        break
    }

    if (processForm.value.details) {
      resultText += `：${processForm.value.details}`
    }

    // 获取当前景点的举报数据
    const query = featureLayer.createQuery()
    query.where = `OBJECTID = ${selectedSpotId.value}`
    query.outFields = ['UncivilizedBehaviorReportMessageJSON', 'UncivilizedBehaviorReportCount']

    const result = await featureLayer.queryFeatures(query)
    if (result.features.length === 0) {
      throw new Error('无法获取景点信息')
    }

    const feature = result.features[0]
    console.log('获取到的景点数据', feature.attributes)

    // 定义举报数据类型
    interface ReportData {
      id: string;
      type: string;
      date: string;
      description: string;
      severity: number;
      imageBase64?: string;
      contact?: string;
      reporter: string;
      status: 'pending' | 'processed';
      processResult?: string;
      processTime?: string;
      reportTime: string;
    }

    // 解析现有的不文明行为信息
    let reportsList: ReportData[] = []
    try {
      if (feature.attributes.UncivilizedBehaviorReportMessageJSON) {
        const parsedData = JSON.parse(feature.attributes.UncivilizedBehaviorReportMessageJSON)
        if (Array.isArray(parsedData)) {
          reportsList = parsedData as ReportData[]
        }
      }
    } catch (e) {
      console.error('解析不文明行为信息失败', e)
      reportsList = []
    }
    console.log('解析后的举报数据', reportsList)

    // 更新当前举报的状态
    const reportIndex = reportsList.findIndex((r) => r.id === currentReport.value.id)
    if (reportIndex !== -1) {
      reportsList[reportIndex].status = 'processed'
      reportsList[reportIndex].processResult = resultText
      reportsList[reportIndex].processTime = new Date().toISOString()
    } else {
      throw new Error('找不到要处理的举报数据')
    }
    console.log('更新后的举报数据', reportsList)

    // 计算待处理的举报数量
    const pendingReports = reportsList.filter(report => report.status === 'pending')
    const pendingCount = pendingReports.length

    console.log(`处理后的待处理举报数量为 ${pendingCount}`)

    // 更新景点数据
    const attributes = {
      OBJECTID: selectedSpotId.value,
      UncivilizedBehaviorReportMessageJSON: JSON.stringify(reportsList),
      UncivilizedBehaviorReportCount: pendingCount // 更新待处理数量
    }
    console.log('更新景点数据', attributes)

    // 创建更新图形
    const updateFeature = new Graphic({
      attributes: attributes
    })

    // 应用编辑
    console.log('开始提交数据更新', updateFeature)
    try {
      const updateResult = await featureLayer.applyEdits({
        updateFeatures: [updateFeature]
      })

      console.log('数据更新结果', updateResult)

      if (updateResult.updateFeatureResults && updateResult.updateFeatureResults.length > 0) {
        // 更新本地数据
        if (reportIndex !== -1) {
          reports.value[reportIndex].status = 'processed'
          reports.value[reportIndex].processResult = resultText
          reports.value[reportIndex].processTime = new Date().toISOString()

          // 更新当前报告
          currentReport.value = reports.value[reportIndex]
        }

        // 更新景点数据中的举报计数
        await updatePendingReportCount(selectedSpotId.value, reportsList)

        ElMessage.success('举报已处理')
        showProcessDialog.value = false

        // 重新加载所有景点数据
        await loadSpots()
      } else {
        console.error('更新结果不包含有效数据', updateResult)
        throw new Error('更新景点数据失败')
      }
    } catch (error) {
      console.error('应用编辑时发生错误', error)
      throw error
    }
  } catch (error) {
    console.error('处理举报失败', error)
    ElMessage.error('处理举报失败')
  } finally {
    processing.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''

  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 更新景点的待处理举报数量
const updatePendingReportCount = async (spotId: number, reportsList: any[]) => {
  try {

    // 计算待处理的举报数量
    const pendingReports = reportsList.filter(report => report.status === 'pending')
    const pendingCount = pendingReports.length

    console.log(`更新景点 #${spotId} 的待处理举报数量为 ${pendingCount}`)

    // 更新景点数据
    const attributes = {
      OBJECTID: spotId,
      UncivilizedBehaviorReportCount: pendingCount // 只计算待处理的举报数量
    }

    // 创建更新图形
    const updateFeature = new Graphic({
      attributes: attributes
    })

    // 应用编辑
    console.log('开始更新待处理数量', updateFeature)
    const updateResult = await featureLayer.applyEdits({
      updateFeatures: [updateFeature]
    })

    console.log('更新待处理数量结果', updateResult)

    // 更新本地数据
    if (selectedSpot.value && selectedSpot.value.OBJECTID === spotId) {
      selectedSpot.value.UncivilizedBehaviorReportCount = pendingCount
    }

    // 更新景点列表中的数据
    const spotIndex = spotList.value.findIndex(spot => spot.OBJECTID === spotId)
    if (spotIndex !== -1) {
      spotList.value[spotIndex].UncivilizedBehaviorReportCount = pendingCount
    }

    return true
  } catch (error) {
    console.error('更新待处理数量失败', error)
    return false
  }
}

// 获取行为类型标签类型
const getBehaviorTypeTag = (type: string): string => {
  const typeMap: Record<string, string> = {
    'graffiti': 'danger',
    'climbing': 'warning',
    'touching': 'warning',
    'littering': 'info',
    'damaging_plants': 'danger',
    'feeding_animals': 'warning',
    'noise': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取行为类型文本
const getBehaviorTypeText = (type: string): string => {
  const typeMap: Record<string, string> = {
    'graffiti': '刻画涂污',
    'climbing': '攀爬古迹',
    'touching': '触摸展品',
    'littering': '乱扔垃圾',
    'damaging_plants': '破坏植被',
    'feeding_animals': '喂食动物',
    'noise': '大声喧哗',
    'other': '其他行为'
  }
  return typeMap[type] || '未知类型'
}
</script>

<style scoped>
.behavior-management-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 32px;
  color: #c62f2f;
  margin-bottom: 10px;
  font-weight: bold;
}

.page-description {
  font-size: 16px;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
}

.spot-list-card,
.report-list-card,
.no-spot-selected {
  margin-bottom: 20px;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 200px;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.status-filter {
  width: 120px;
}

.empty-reports {
  padding: 40px 0;
}

.report-details {
  padding: 20px;
}

.drawer-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.process-result {
  padding: 20px 0;
}

.process-result p {
  margin-bottom: 10px;
  line-height: 1.6;
}

.full-width {
  width: 100%;
}

.no-spot-selected {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

/* 举报数量徽章样式 */
.report-count-badge {
  display: inline-block;
  min-width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #f56c6c;
  color: white;
  border-radius: 12px;
  padding: 0 8px;
  font-size: 12px;
  font-weight: bold;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .behavior-management-container {
    padding: 10px;
  }

  .search-input,
  .status-filter {
    width: 100%;
    margin-top: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    margin-top: 10px;
  }
}
</style>
